<template>
	<view class="reservePage">
		<view class="head" :style="[{ height: customBar + 'px' }]">
			<u-navbar title="场地预定" :autoBack="true" :titleStyle="{ fontSize: '34rpx', fontWeight: '500' }"></u-navbar>
		</view>
		<view class="reserveTop">
			<view class="reserveTab">
				<view class="tabList" v-for="(item, i) in tabList" :key="i" @click="tabIndex = i"
					:class="tabIndex == i ? 'select1' : ''">
					<view>
						<view>{{ item.name }}</view>
						<view class="day">{{ item.day }}</view>
					</view>
				</view>
			</view>
			<view v-if="tabIndex == 1">
				<view class="tabTime">
					<view v-for="(i, v) in days" :key="i" @click="handleWeek(v)"
						:class="tabWeek == v ? 'active' : 'timeWeek'">
						<view class="week">{{ i.week_text }}</view>
						<view class="date">{{ i.date_text }}</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="tabIndex == 1">
			<view class="morning">上午（可多选）</view>
			<view class="morningData">
				<view class="list">
					<view v-for="(item, i) in morningSlots" :key="i"
						:class="['morningTime', { active: isSelected(item.text) }]" @click="selectSlot(i, 'morning')">
						{{ item.text }}
					</view>
				</view>
			</view>
			<view class="morning">下午（可多选）</view>
			<view class="morningData">
				<view class="list">
					<view v-for="(item, i) in afternoonSlots" :key="i"
						:class="['morningTime', { active: isSelected(item.text) }]" @click="selectSlot(i, 'afternoon')">
						{{ item.text }}
					</view>
				</view>
			</view>
			<view style="height: 220rpx"></view>
			<view class="footer">
				<view class="total">
					合计预定时长：
					<view class="time">{{ totalTime }}小时</view>
				</view>
				<view class="money" @click="handlePay">支付{{ totalMoney }}元</view>
			</view>
		</view>
		<!-- 第一部分結束 -->
		<view v-if="tabIndex == 0">
			<view class="second">
				<image class="img" src="@/static/reservation/title.png" mode="widthFix"></image>
				选择预定日期
			</view>
			<view class="calendars">
				<u-calendars :show="show" mode="multiple" :maxDate="maxDate" @confirm="confirm"
					color="#A3C616"></u-calendars>
			</view>
			<view class="footer">
				<view class="total">
					合计选择天数：
					<view class="time">{{ dayNum }}天</view>
				</view>
				<view class="money" @click="handlePay">支付{{ daytotalMoney }}元</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import uCalendars from "@/uni_modules/uview-ui/components/u-calendars/u-calendars.vue";
	export default {
		components: {
			uCalendars,
		},
		data() {
			return {
				tabIndex: 0,
				tabWeek: 0,
				customBar: 88,
				tabList: [{
						name: "按天",
						day: "（150/天）",
					},
					{
						name: "按小时",
						day: "（70/小时）",
					},
				],
				morningSlots: [],
				afternoonSlots: [],
				selectedSlots: [], // 存储已选择的时间段
				currentPeriod: null, // 当前选择的时间段所属的时间段（上午或下午）
				show: true,
				dayNum: 0,
				id: "",
				days: [],
				day_price: "10",
				hours_price: "10",
				daytotalMoney: "",
				dayArr: [],
				maxDate: new Date(
					new Date().getFullYear(),
					new Date().getMonth() + 1,
					new Date().getDate()
				),
				totalDta1: [],
			};
		},
		computed: mapGetters(["isLogin", "uid", "userInfo"]),
		onLoad(params) {
			this.id = params.id;
			this.getDetail(params.id);
		},
		mounted() {
			this.getDatestadium();
		},
		computed: {
			totalTime() {
				return this.selectedSlots.length / 2;
			},
			totalMoney() {
				return this.totalTime * this.hours_price;
			},
		},

		methods: {
			// 检查时间段是否相邻


			// 检查选择的时间段是否有效
			isValidSelection(currentItem, period) {
				if (this.selectedSlots.length === 0) {
					// 第一个选择总是有效的
					return true;
				}
				const originalData = (period === 'morning') ? this.morningSlots : this.afternoonSlots;


				const lastItem = this.selectedSlots[this.selectedSlots.length - 1];
				const fastItem = this.selectedSlots[0];
				// 检查是否相邻
				const fastIndex = originalData.findIndex(item => item.text === fastItem.text);
				const lastIndex = originalData.findIndex(item => item.text === lastItem.text);
				const currentIndex = originalData.findIndex(item => item.text === currentItem.text);

				// 检查索引是否连续且当前索引大于最后索引
				return currentIndex === lastIndex + 1 || currentIndex === fastIndex - 1;

			},

			selectSlot(index, period) {
				const slot = (period === 'morning') ? this.morningSlots[index] : this.afternoonSlots[index];
				// 检查是否属于同一时间段（上午或下午）
				if (this.currentPeriod !== null && this.currentPeriod !== period) {
					// 尝试选择不同时间段（上午或下午）的时间段
					this.$Toast('不能同时选择上午和下午的时间段')
					return;
				}


				let selectedSlots = this.selectedSlots.map(item => {
					return item.text
				})
				const selectIndex = selectedSlots.indexOf(slot.text);

				if (selectIndex != -1) {
					if (selectIndex != 0 && selectIndex != selectedSlots.length - 1) {
						this.$Toast('无法从中间取消所选时间段')
						return;
					}
					this.selectedSlots.splice(selectIndex, 1);
					if (this.selectedSlots.length == 0) {
						period = null;
					}
				} else {
					if (!this.isValidSelection(slot, period)) {
						// 时间段不相邻或不属于同一时间段
						this.$Toast('只能选择相邻的时间段')
						return;
					}
					this.selectedSlots.push({
						...slot,
						index,
						period
					});
					this.selectedSlots = this.selectedSlots.sort((a, b) => a.index - b.index);
					console.log(this.selectedSlots, 9999)
				}
				this.currentPeriod = period;
			},
			// 重置选择
			resetSelection() {
				this.selectedSlots = [];
				this.currentPeriod = null;
			},
			isSelected(time) {
				let selectedSlots = this.selectedSlots.map(item => {
					return item.text
				})
				return selectedSlots.includes(time);
			},
			getDatestadium() {
				this.$Api.reservation.getDatestadium().then((res) => {
					this.days = res.data;
					this.morningSlots = res.data[this.tabWeek].time_interval.top;
					this.afternoonSlots = res.data[this.tabWeek].time_interval.afternoon;
				});
			},
			getDetail(id) {
				this.$Api.reservation.stadiumDetail({
					id: id,
				}).then((res) => {
					this.day_price = res.data.day_price;
					this.hours_price = res.data.hours_price;
					this.tabList[0].day = "（" + res.data.day_price + "/天）";
					this.tabList[1].day = "（" + res.data.hours_price + "/小时）";
					this.daytotalMoney = res.data.day_price;
				});
			},
			handleWeek(i) {
				this.tabWeek = i;
				this.resetSelection()
				this.getDatestadium();
			},

			confirm(e) {
				this.show = false;
				this.dayNum = e.length;
				this.dayArr = e;
				this.daytotalMoney = this.dayNum * this.day_price;
			},
			handlePay() {
				let selectedSlots = this.selectedSlots.map(item => {
					return item.date
				})
				if (this.tabIndex == 1 && selectedSlots.length < 2) {
					this.$Toast('请至少选择两个时间段进行预约')
					return;
				}
				uni.navigateTo({
					url: "/pages/reservation/orderDetail?id=" + this.id +
						"&money=" + this.daytotalMoney +
						"&dayMoney=" + this.totalMoney +
						"&dayArr=" + this.dayArr +
						"&selected=" + selectedSlots.join(',') +
						"&tabWeek=" + this.days[this.tabWeek].dd +
						"&type=" + this.tabIndex,
				});
			},
		},
	};
</script>

<style lang="scss">
	.reservePage {
		height: 100%;
		min-height: 100vh;
		font-family: PingFang SC;
		background: #f5f5f4;

		.reserveTop {
			background: #fff;

			.tabTime {
				width: 100%;
				overflow-x: auto;
				display: flex;
				align-items: center;
				margin-top: 42rpx;
				padding-left: 32rpx;
				padding-bottom: 30rpx;

				.timeWeek {
					width: 116rpx;
					height: 116rpx;
					color: #303030;
					font-size: 26rpx;
					background: #f6f6f8;
					border-radius: 24rpx;
					text-align: center;
					margin-right: 20rpx;
					flex-shrink: 0;

					.week {
						margin-top: 16rpx;
					}

					.date {
						font-size: 36rpx;
						color: #000;
						font-weight: 600;
					}
				}

				.active {
					width: 112rpx;
					height: 112rpx;
					border: 1rpx solid #a3c616;
					background: #fbffed;
					border-radius: 24rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 600;
					text-align: center;
					font-size: 26rpx;
					margin-right: 20rpx;
					flex-shrink: 0;

					.week {
						margin-top: 16rpx;
						color: #a3c616;
					}

					.date {
						font-size: 36rpx;
						color: #a3c616;
						font-weight: 600;
					}
				}
			}
		}

		.reserveTab {
			width: 100%;
			height: 132rpx;
			background: linear-gradient(360deg, #ffffff 0%, #f5ffcf 100%);
			box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0, 0, 0, 0.05);
			border-radius: 40rpx 40rpx 0rpx 0rpx;
			margin-top: 22rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.select1:nth-child(1) {
				width: 50%;
				height: 100%;
				background: url("../../static/reservation/select1.png") no-repeat;
				background-size: 100% 100%;
				color: #5a7004;
			}

			.select1:nth-child(2) {
				width: 50%;
				height: 100%;
				background: url("../../static/reservation/select2.png") no-repeat;
				background-size: 100% 100%;
				align-items: center;
				color: #5a7004;
			}

			.tabList {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				text-align: center;
				font-size: 36rpx;
				color: #232624;

				.day {
					font-size: 28rpx;
				}
			}
		}

		.morning {
			width: 94%;
			height: 88rpx;
			background: #ffffff;
			box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(255, 255, 255, 0.15);
			border-radius: 12rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-weight: 500;
			font-size: 32rpx;
			color: #323334;
			margin-top: 22rpx;
			margin-left: 3%;
		}

		.morningData {
			.list {
				width: 94%;
				margin-left: 3%;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				margin-top: 20rpx;

				.morningTime {
					padding: 24rpx 27rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #323334;
					text-shadow: 0px 4px 8px rgba(255, 255, 255, 0.15);
					text-align: center;
					background: #fff;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
					box-sizing: border-box;
				}

				.morningTime:nth-child(3n),
				.active:nth-child(3n) {
					margin-right: 0;
				}

				.active {
					padding: 24rpx 27rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					background: #a3c616;
					color: #fff;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
				}
			}
		}

		.second {
			display: flex;
			align-items: center;
			font-weight: 800;
			font-size: 36rpx;
			color: #000000;
			line-height: 50rpx;
			padding: 30rpx;
			box-sizing: border-box;

			.img {
				width: 25rpx;
				vertical-align: middle;
				margin-right: 10rpx;
			}
		}

		.u-calendar-header__title {
			display: none;
		}

		.calendars {
			width: 92%;
			height: 53vh;
			margin: 20rpx auto;
			background: #ffffff;
			box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0, 0, 0, 0.1);
			border-radius: 20rpx;
		}

		.footer {
			width: 100%;
			height: 216rpx;
			position: fixed;
			// bottom: calc(env(safe-area-inset-bottom) / 2);
			bottom: 0;
			background: #fff;
			box-shadow: 0rpx -4rpx 8rpx 0rpx rgba(0, 0, 0, 0.1);
			padding: 20rpx 38rpx;
			box-sizing: border-box;

			.total {
				display: flex;
				font-weight: 400;
				font-size: 28rpx;
				color: #000000;

				.time {
					font-weight: bold;
					font-size: 34rpx;
					color: #a3c616;
				}
			}

			.money {
				width: 100%;
				height: 88rpx;
				line-height: 88rpx;
				text-align: center;
				color: #fff;
				background: #a3c616;
				box-shadow: 0rpx 4rpx 12rpx 0rpx rgba(163, 198, 22, 0.3);
				border-radius: 24rpx;
				font-weight: 500;
				font-size: 34rpx;
				margin-top: 18rpx;
			}
		}
	}
</style>